package com.gdut.simple.data.remote.http.service.impl;

import com.gdut.simple.common.LogUtils;
import com.gdut.simple.common.RequestCallback;
import com.gdut.simple.data.remote.api.NewsApi;
import com.gdut.simple.data.entity.News;
import com.gdut.simple.data.entity.Result;
import com.gdut.simple.data.remote.http.service.INewService;
import com.gdut.simple.data.remote.http.core.ServiceFactory;

import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class NewsApiService {

    public static void getNews(String type, int page, int num, final RequestCallback<List<News>> callback) {
        ServiceFactory.createService(NewsApi.TIAN_BASE_URL, INewService.class)
                .getNews(type, page, num)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .onErrorReturn(new Func1<Throwable, Result<List<News>>>() {
                    @Override
                    public Result<List<News>> call(Throwable throwable) {
                        LogUtils.e("Http", "call onError");
                        if (callback != null) {
                            callback.onFailure(throwable.getMessage());
                        }
                        return null;
                    }
                })
                .map(new Func1<Result<List<News>>, List<News>>() {
                    @Override
                    public List<News> call(Result<List<News>> result) {
                        if (result != null) {
                            LogUtils.e("Http", "response code:" + result.getCode() + "--response message--" + result.getMessage());
                            if (result.getCode() == 0 && result.getResult() != null) {
                                return result.getResult();
                            }
                        }
                        return null;
                    }
                })
                .subscribe(new Action1<List<News>>() {
                    @Override
                    public void call(List<News> newses) {
                        if (newses == null) {
                            if (callback != null) {
                                callback.onFailure("null");
                            }
                            return;
                        }
                        if (callback != null) {
                            callback.onSuccess(newses);
                        }
                    }
                });
    }

}
